package com.songcha.sakura.mvvm.home.home

import com.songcha.library_base.mvvm.base.BaseRepository
import com.songcha.library_common.helper.SharedPreferenceHelper
import com.songcha.sakura.bean.ComicListBean
import com.songcha.sakura.bean.HomeBannerListBean
import com.songcha.sakura.config.BaseConfig
import com.songcha.library_database_sakura.greendao.*
import io.reactivex.Observable
import org.jsoup.Jsoup

class HomeRepository : BaseRepository()  {

    fun getSearchHistory():Observable<MutableList<SearchHistoryBean>>{
        //显示搜索历史
        val searchHistoryDao=GreenDaoManager.getInstance().searchHistoryDao
        val qb=searchHistoryDao.queryBuilder()
        qb.orderDesc(SearchHistoryBeanDao.Properties.Id)
        qb.limit(10)
        //val list=searchHistoryDao.loadAll()
        val list=qb.list()
        return Observable.just(list)
    }

    private fun getComicThumb(href:String):Observable<String>{

        return Observable.create{
            val document=Jsoup.connect("${BaseConfig.BASE_URL_WINDMILL}"+href).get()
            val splay=document.getElementsByClass("thumb l")[0]

            if(splay.childrenSize()<2) {
                it.onNext("")
                it.onComplete()
                return@create
           }
            val thumb="https:"+splay.child(1).attr("src")
            it.onNext(thumb)
            it.onComplete()
        }
    }

    fun updateBannerList():Observable<HomeBannerListBean>{
        return createNetworkObservable{
            val homeBannerCacheDao=GreenDaoManager.getInstance().homeBannerCacheDao
            //val qb=homeBannerCacheDao.queryBuilder()
            val list=homeBannerCacheDao.loadAll()
            //val list=qb.list()
            //val cacheBean= HomeBannerCacheBean()
            val data=mutableListOf<HomeBannerListBean.HomeBannerBean>()
            for(item in list){
                data.add(HomeBannerListBean.HomeBannerBean(item.title,item.href,item.img,item.desc))
            }
            val bean=HomeBannerListBean(data)
            it.onNext(bean)
            it.onComplete()
        }
    }

    fun saveBannerListDB(bean:HomeBannerListBean){
        val homeBannerCacheDao= GreenDaoManager.getInstance().homeBannerCacheDao
        val qb=homeBannerCacheDao.queryBuilder()
        //val list=homeBannerCacheDao.loadAll()
        val list=qb.list()

        if(list.size>0){
            qb.where(HomeBannerCacheBeanDao.Properties.Id.isNotNull)
            qb.buildDelete().executeDeleteWithoutDetachingEntities()
        }

        for(item in bean.data){
            val cacheBean= HomeBannerCacheBean()
            cacheBean.title=item.title
            cacheBean.href=item.href
            cacheBean.img=item.img
            cacheBean.desc=item.desc
            homeBannerCacheDao.insert(cacheBean)
        }

        SharedPreferenceHelper.setInt("home_cache","banner_cache_time",(System.currentTimeMillis()/1000).toInt())
    }

    fun getBannerList():Observable<HomeBannerListBean>{
        //if(list.size==0) return Observable.just(HomeBannerListBean(mutableListOf()))

       /* val ol=mutableListOf<Observable<String>>()
        val newList=mutableListOf<ComicListBean.ComicBean>()
        for(item in list){
            if(item.update.contains("new")){
                ol.add(getComicThumb(item.href))
                newList.add(item)
            }
        }

        return Observable.zip(ol,object :Function<Array<Any>,HomeBannerListBean>{
                override fun apply(t: Array<Any>): HomeBannerListBean {
                    val data=mutableListOf<HomeBannerListBean.HomeBannerBean>()
                    for(i in t.indices){
                        val img=t[i] as String
                        val item=newList[i]
                        data.add(HomeBannerListBean.HomeBannerBean(item.title,item.href,img,item.describe))
                    }
                    return HomeBannerListBean(data)
                }
            })*/


        //val obs=Observable.zip(ol){

           /*   val data=mutableListOf<HomeBannerListBean.HomeBannerBean>()
              for(i in it.indices){
                  val item=it[i] as String
                  //data.add(HomeBannerListBean.HomeBannerBean(it,item,img,desc))
              }

              val bean=HomeBannerListBean(data)*/

         // }



        return createNetworkObservable{
            val document=Jsoup.connect("${BaseConfig.BASE_URL_WINDMILL}").get()
            val data=mutableListOf<HomeBannerListBean.HomeBannerBean>()

           /* val elements=document.getElementsByClass("pics")[0].getElementsByTag("ul")
            for(i in 0 until elements.size){
                val ul=elements[i]
                val lis=ul.getElementsByTag("li")
                for(j in 0 until lis.size){
                    val li=lis[j]
                    val a=li.child(0)
                    val href=a.attr("href")
                    val img=a.child(0).attr("src")
                    val title=a.child(0).attr("alt")
                    //val desc=a.child(1).text()
                    val desc=""
                    data.add(HomeBannerListBean.HomeBannerBean(title,href,img,desc))
                }
            }*/


            val elements=document.getElementsByClass("hero-wrap")[0].getElementsByTag("ul")
            for(i in 0 until elements.size){
                val ul=elements[i]
                val lis=ul.getElementsByTag("li")
                for(j in 0 until lis.size){
                    val li=lis[j]
                    val a=li.child(0)
                    val href=a.attr("href")
                    val title=a.attr("title")
                    val img=a.child(0).attr("src")
                    val desc=a.child(1).text()
                    data.add(HomeBannerListBean.HomeBannerBean(title,href,img,desc))
                }
            }
            val bean=HomeBannerListBean(data)
            it.onNext(bean)
            it.onComplete()
        }


    }

    fun updateHomeCache(warmBlood:ComicListBean,fight:ComicListBean){
        val homeCacheDao=GreenDaoManager.getInstance().homeCacheDao
        val list=homeCacheDao.loadAll()
        val bean= HomeCacheBean()

        bean.warmBlood=warmBlood.toString()
        bean.fight=fight.toString()
        //bean.love=(update_cache_list["2"] as ComicListBean).toString()

        if(list.size==0){
            homeCacheDao.insert(bean)
        }else{
            bean.id=list[0].id
            homeCacheDao.update(bean)
        }

        //update_cache_list.clear()
        SharedPreferenceHelper.setInt("home_cache","cache_time",(System.currentTimeMillis()/1000).toInt())
    }

}